import { defineStore } from 'pinia'
import { ref } from 'vue'
import { userApi } from '../utils/api'

export const useUserStore = defineStore('user', () => {
  const user = ref(null)
  const isLoggedIn = ref(false)

  const login = async (credentials) => {
    const response = await userApi.login(credentials)
    if (response.data) {
      user.value = response.data
      isLoggedIn.value = true
      localStorage.setItem('user', JSON.stringify(response.data))
    }
    return response
  }

  const register = async (userData) => {
    const response = await userApi.register(userData)
    return response
  }

  const logout = () => {
    user.value = null
    isLoggedIn.value = false
    localStorage.removeItem('user')
  }

  // 初始化时检查本地存储
  const init = () => {
    const savedUser = localStorage.getItem('user')
    if (savedUser) {
      user.value = JSON.parse(savedUser)
      isLoggedIn.value = true
    }
  }

  return { user, isLoggedIn, login, register, logout, init }
})